package br.edu.utfpr.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import br.edu.utfpr.app.beans.Cliente;
import br.edu.utfpr.app.dto.ClienteDTO;
import br.edu.utfpr.view.ServidorView;
import br.edu.utfpr.view.action.Action;
import br.edu.utfpr.view.action.ActionCliente;
import br.edu.utfpr.view.action.ControladorAcao;

public class Server extends Thread implements Serializable{

	private static final long serialVersionUID = 1L;
	
	ObjectInputStream input = null;
	ObjectOutputStream output = null;
	
	ServerSocket server = null;
	Socket connection = null;
	
	Object object = null;
	String message;
	
	ControladorAcao acao;

	public Server(String nome) {
		super(nome);
	}

	public void iniciar() {

		try {
			if (connection == null) {
				int port = Integer.parseInt("56551");
				server = new ServerSocket(port);

				message = "";
				this.start();

				ServidorView.addLog("Servidor ativo e escutando a porta "+ port);
			} else {
				ServidorView.addLog("O Servidor já está iniciado");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}

	}
	
	@Override
	public void run() {
		while (!message.equals("fim")) {
			try {
				connection = server.accept();
				input = new ObjectInputStream(connection.getInputStream());
				output = new ObjectOutputStream(connection.getOutputStream());
				
				message = input.readUTF();
				Object object = input.readObject();
				
				Object retorno = new ControladorAcao(message, object).execute();
				output.writeObject(retorno);
				output.writeUTF(ServidorView.getLastLog());
				
				output.flush();
				input.close();
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	public void parar() throws IOException {
		if (connection != null) {
			connection.close();
			server.close();
			input.close();
			output.close();

			message = "fim";
			ServidorView.addLog("Servidor parado");
		} else {
			ServidorView.addLog("O servidor já está parado");
		}
	}

}
